package com.pj.main;

import java.io.*;
import java.net.*;

public class DataCollector {
    public static void main(String[] args) {
        try {
            // 创建服务端 Socket
            ServerSocket serverSocket = new ServerSocket(8083);
            System.out.println("服务端已启动,等待客户端连接...");

            // 连接客户端

            // 接受客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接");

            // 获取输入流,读取数据
            InputStream inputStream = clientSocket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            // 创建输出文件流,保存数据
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\data.txt", true);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("收到数据: " + line);
                writer.write(line);
                writer.newLine();
                writer.flush();
            }

            // 关闭资源
            writer.close();
            reader.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}